package com.southgis.ibase.sql.builder;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

import lombok.Data;

/**
 * 表字段描述信息
 * @author dnnyo
 *
 */
@Data
public class TableColumn
{
	private Table table;
	private String name;
	private String alias;
	
	public TableColumn(Table table, String fname, String falias)
	{
		this.table=table;
		this.name=fname;
		this.alias=falias;
	}
	
	public TableColumn(String fname, String falias)
	{
		this((Table)null, fname, falias);
	}
	
	public TableColumn(String tableName, String fname, String falias)
	{
		this.name=fname;
		this.alias=falias;
		if(!StringUtils.isEmpty(tableName)) {
			table=new SimpleTable(tableName, null);
		}
	}
	
	public static TableColumn of(String fname)
	{
		return new TableColumn(fname, "");
	}
	
	/**
	 * 根据不同区段生成字符串
	 * @param section 在哪个区段生成(SqlBuilder.BUILD_SECTION_XXX):0-select，1-where|having，2-XBy，3-join|from，
	 *  4-insert-fields|delete
	 * @param sb
	 */
	public void toSql(int section, StringBuilder sb)
	{
		//如果在xx by子句中，有别名用别名，无别名用原字段名
		if(section==SqlBuilder.BUILD_SECTION_XBY) {
			if(!StringUtils.isEmpty(alias))
				sb.append(alias);
			else
				fillName(sb);
			return;
		}
		
		fillName(sb);
		if(section==SqlBuilder.BUILD_SECTION_SEUPDATE) {
			if(!StringUtils.isEmpty(alias))
			{
				sb.append(" as ");
				sb.append(alias);
			}
		}
	}
	
	protected void fillName(StringBuilder sb)
	{
		if(table!=null)
			sb.append(table.getAlias()).append(".");
		sb.append(name);
	}
	
	@Override
	public boolean equals(Object obj)
	{
		if(obj==null) return false;
		if(this==obj) return true;
		if(!(obj instanceof TableColumn)) return false;
		TableColumn comp=(TableColumn)obj;
		return Objects.equals(this.table, comp.table) && Objects.equals(this.name, comp.name);
	}
	@Override
	public int hashCode()
	{
		return Objects.hash(this.getClass(), this.table, this.name);
	}
	
	@Override
	public String toString()
	{
		return (table==null?"":(table.toString()+"."))+this.name+"["+alias+"]";
	}
}